#/usr/bin/ruby

class TagCloud
  attr_accessor :words

  def initialize(words = [])
    @words = {}
    self.add(words)
  end

  def add(words)
    words.each do |word|
      w = word.strip
      if @words.key?(w)
        @words[w] = @words[w] + 1
      else
        @words[w] = 1
      end
    end
  end

  def calc(level = 24)
    return {}  if @words.empty?

    min = @words.to_a.min {|a, b| a[1] <=> b[1]}.at(1)
    max = @words.to_a.max {|a, b| a[1] <=> b[1]}.at(1)

    if max == min
      min = min - level
      ratio = 1
    else
      ratio = level / (Math.sqrt(max) - Math.sqrt(min))
    end

    wordcount = {}

    @words.each_key do |word|
      wordcount[word] = ((Math.sqrt(@words[word]) - Math.sqrt(min)) * ratio).to_i
    end

    wordcount
  end
end

if $0 == __FILE__
  tagcloud = TagCloud.new

  data = [
    "foo", "foo", "foo", "foo",
    "bar", "bar",
    "baz",
  ]

  data.each do |d|
    tagcloud.add(d)
  end

  tagcloud.calc.each_pair do |key, value|
    puts "#{key} ... #{value}"
  end
end

